<script setup lang='ts'>
import { ref, type Ref } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useUserStore } from "@/stores/useUserStore";

const form = ref<Ref | null>(null)

import useRule from "./useRule";
import useLogin from "./useLogin";
import { getTokenStore } from "@/utils/storage/tokenStore";
import { ResponseCode } from "@/common/Responsetypes";

// 表单规则
const { rules } = useRule()

// 处理 登录
const { userInfo, handleLogin } = useLogin()

// 显示密码
const showPassword = ref(false)

onShow(() => {
  const { userInfo, whoami } = useUserStore()
  if (userInfo !== null) {
    toHome()
    return
  }

  const token = getTokenStore()
  if (token) {
    whoami().then((res) => {
      if (res.code === ResponseCode.PASS) {
        toHome()
      }
    })
  }

  function toHome() {
    uni.showLoading()
    setTimeout(function () {
      uni.hideLoading();
      uni.reLaunch({
        url: "/pages/index/index"
      })
    }, 1000);
  }

})

function toModifyPassword() {
  uni.navigateTo({
    url: "/pages/modify-password/modify-password"
  })
}

</script>

<template>
  <view class='login__container plr-40 pt-40'>

    <headerBar text="登录体验更多精彩"></headerBar>
    <view class="login-input__area plr-20 pt-12">
      <uv-form :model="userInfo" ref="form" :rules="rules">
        <uv-form-item prop="email" borderBottom>
          <uv-input maxlength="70" placeholder="邮箱" v-model="userInfo.email" border="none">
          </uv-input>
        </uv-form-item>
        <uv-form-item prop="password" borderBottom>
          <uv-input placeholder="密码" maxlength="18" :password="!showPassword" v-model="userInfo.password" border="none">
          </uv-input>
          <template v-slot:right>
            <uv-icon name="eye" @click="showPassword = !showPassword" :color="showPassword ? '#2979ff' : ''"
              size="28"></uv-icon>
          </template>
        </uv-form-item>
      </uv-form>


      <view @click="toModifyPassword" class="mtb-40 login-input__ignore" style="text-align: right; ">
        忘记密码
      </view>
      <view class="input-operator mt-20">
        <uv-button @click="handleLogin(form)" type="primary" text="登录"></uv-button>
        <navigator class="mt-20" url="/pages/register/register">
          <uv-button type="info" text="注册"></uv-button>
        </navigator>
      </view>
    </view>
  </view>
</template>

<style scoped lang='scss'>
@import "./login.scss";
</style>@/common/Responsetypes